package com.example.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.library.entity.Book;
import com.example.library.entity.Borrowing;
import com.example.library.mapper.BookMapper;
import com.example.library.mapper.BorrowingMapper;
import com.example.library.service.IBorrowingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.Collection;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@Service
public class BorrowingServiceImpl extends ServiceImpl<BorrowingMapper, Borrowing> implements IBorrowingService {
    @Autowired
    private BookMapper bookMapper;

    public boolean borrowBook(Integer userId, Integer bookId) {
        // 查找书籍
        Book book = bookMapper.selectByID(bookId);
        if (book == null) {
            throw new RuntimeException("Book not found");
        }

        // 检查书籍库存
        if (book.getCount() <= 0) {
            throw new RuntimeException("Book is out of stock");
        }

        Date borrowDate = new Date(System.currentTimeMillis());

        // 创建借阅记录
        Borrowing borrowing = new Borrowing();
        borrowing.setUserid(userId);
        borrowing.setBookid(bookId);
        borrowing.setBorrowdate(borrowDate);
        borrowing.setReturndate(null);  // 还书日期为空，表示尚未归还

        // 保存借阅记录
        boolean isSaved = this.save(borrowing);
        if (!isSaved) {
            throw new RuntimeException("Failed to save borrowing record");
        }

        // 更新书籍库存
        book.setCount(book.getCount() - 1);
        int isBookUpdated = bookMapper.updateByPrimaryKey(book);
        if (isBookUpdated != 0) {
            throw new RuntimeException("Failed to update book stock");
        }

        return true;  // 借阅成功
    }

    @Override
    public boolean returnBook(Integer userId, Integer bookId) {
        // 查找借阅记录
        Borrowing borrowing = this.getActiveBorrowing(userId, bookId);
        if (borrowing == null) {
            throw new RuntimeException("Borrowing record not found");
        }

        Date returnDate = new Date(System.currentTimeMillis());
        // 设置归还日期
        borrowing.setReturndate(returnDate);

        // 更新借阅记录
        boolean isUpdated = this.updateById(borrowing);
        if (!isUpdated) {
            throw new RuntimeException("Failed to update borrowing record");
        }

        // 更新书籍库存
        Book book = bookMapper.selectByID(bookId);
        book.setCount(book.getCount() + 1);  // 增加书籍库存
        int isBookUpdated = bookMapper.updateByPrimaryKey(book);
        if (isBookUpdated != 0) {
            throw new RuntimeException("Failed to update book stock");
        }

        return true;  // 归还成功
    }

    // 根据用户ID和书籍ID查找借阅记录
    public Borrowing getActiveBorrowing(Integer userId, Integer bookId) {
        return this.baseMapper.selectOne(
                new QueryWrapper<Borrowing>()
                        .eq("user_id", userId)
                        .eq("book_id", bookId)
                        .isNull("returndate")  // 归还日期为空，表示未归还
        );
    }
}
